/* eslint-disable */
import { Toast, Indicator } from 'mint-ui';
import axios from 'axios'
import qs from "qs"
import utils from './util'
import router from '@/router';
import { is_login, getToken, wechatLogin,jumpLogin} from './user'
import {
    // localStorage as LsyStorage,
    cookie as LsyCookie
} from 'lsy-storages';

/*防止重复请求参数*/
let cancel ,promiseArr = {};
const CancelToken = axios.CancelToken;
let baseUrl = '/api/';
let host = '';
// 创建axios默认请求
const $http = axios.create({
    baseURL: "/api/",
    timeout: 30000, // request timeout,
    withCredentials: true, // 默认的
});

//共有参数可以放在这里
const commonParams = {};
// 请求拦截
$http.interceptors.request.use(config => {
    // 为了防止重复请求ajax  当前请求的url为键 值为取消函数
    if (promiseArr[config.url]) {
        promiseArr[config.url]('操作取消')
        promiseArr[config.url] = cancel
    } else {
        promiseArr[config.url] = cancel //此cancel必须在创建请求的时候 创建好
    }
    // 拼接公共参数
    config.params = Object.assign({},commonParams,config.params)
    //当为传统接收方式post的时候对参数进行序列化
    if (config.method === "post" || config.method === "put" || config.method === "delete") {
        // 序列化
        config.headers['Content-Type'] = "application/x-www-form-urlencoded;charset=utf-8";
        config.data = qs.stringify(config.data); //转化为formdata
    }
    config.headers['TOKEN'] = getToken(); // 让每个请求携带token-- ['Token']为自定义key 请根据实际情况自行修改
    // config.headers['Cookie'] = qs.stringify(LsyCookie.getAll())
    return config
}, error => {
    // Do something with request error
    console.log('请求拦截错误')
    console.log(error) // for debug
    Promise.reject(error)
});


// 相应拦截
//添加一个返回拦截器
$http.interceptors.response.use(function(response){
    //对返回的数据进行一些处理
    return response.data;
},function(error){
    console.log('响应拦截错误');
    return Promise.reject(error);
});

const getUrl = function (url, meta) {
    console.log(meta);
    try
    {
        return meta['url'][url];
    }
    catch(err)
    {
        console.log('请正确配置链接')
        throw new Error('请正确配置链接')
    }
};

const urlLogin = function(requestUrl) {
    try
    {
        let login = requestUrl['login'];
        if (login === 'yes') {
            if (is_login() === false) {
                //重定向到登陆页面
                router.push('/m/login')
                Toast('请先登陆');
                return false;
            }
        }

        return true;
    }
    catch(err)
    {
        throw new Error('请正确配置链接')
    }
};


async function $ajax (url=null,$meta,data = {},
    {
        success = null,
        fail = false,  //自己处理异常
        complete = null,
        errorTips = true,  //错误提示
        successTips = false, //正确提示
        loading = '加载中...',  //是否开启加载提示
        options = {},
    } = {},
    {
        params = {}, //拼接到url上的数据
        methods = 'post',
        headers = {
            'Content-Type': 'application/x-www-form-urlencoded'
        },
    }={},

) {
    let requestUrl = null;
    try {
        if(/^https?/.test(url)){
            requestUrl = {
                url: url
            }
        }else{
            requestUrl = getUrl(url, $meta);
        }
       
        console.log("opt-loading", loading)
        if (loading !==false) {
            let loadingObj;
            if (utils.isString(loading)) {
                loadingObj = {
                    text: loading,
                }
            }  else {
                loadingObj = {
                    text: '加载中',
                    ...loading
                }
            }
            Indicator.open(loadingObj);
        }
    } catch(error) {
        return new Promise((resolve, reject) => {
            reject({
                code: 0,
                msg: error.message
            });
        }); //打断程序
    }

    // 构造请求体
    let request = {
        url: requestUrl.url,
        method: ['get', 'post'].indexOf(methods) > -1 ? methods : 'post',
        headers: Object.assign({
            // set something global
        }, headers),
        data: Object.assign({

        }, data),
        params: params,
        cancelToken: new CancelToken(c => {
            cancel = c
        })
    };
    request = Object.assign(request,options);

    // 发起请求
    return new Promise((resolve, reject) => {
        $http({
            ...request
        }).then(res => {
            Indicator.close();
            utils.isFunc(complete) && complete({
                ...res
            });
            if (res.code === 1) {
                utils.isFunc(success) && success({
                    ...res
                });
                if (successTips) { //正确提示
                    Toast(res.msg ? res.msg : '请求成功');
                }
                resolve(res)
            } else if(res.code === 0) {
                utils.isFunc(fail) && fail({
                    ...res
                });

                //错误的时候 给与提示
                if (errorTips) {
                    Toast(res.msg ? res.msg : '请求失败');
                }

                //如果定义catch 用catch
                if(fail === true) {
                    reject(res)  //把 后台返回的状态码为0的请求 做屏蔽 让最外层 当作异常处理
                }
            } else if (res.code === 401||res.code === 2){
                Toast('请先登陆');
                //如果定义catch 用catch
                if(fail === true) {
                    reject(res)  //把 后台返回的状态码为0的请求 做屏蔽 让最外层 当作异常处理
                }
            }
        }).catch(error=>{
            console.log("error",error.response);
            Indicator.close();
            utils.isFunc(complete) && complete(error);
            if (axios.isCancel(error)) {
                console.log('cacel');
            } else {
                if(error.response && error.response.status == 401){
                    jumpLogin();
                    //如果定义catch 用catch
                    if(fail === true) {
                        reject(error.response.data)  //把 后台返回的状态码为0的请求 做屏蔽 让最外层 当作异常处理
                    }
                    return false
                }
                if (errorTips) { //给与提示
                    Toast('运行出错');
                } else {
                    console.log('运行出错')
                }
                //如果定义catch 用catch
                if(fail === true) {
                    reject({code:0,msg:'系统出错',data:error})  //抛出异常自行处理
                }
            }
        })
    });
};

async function $upload ({
    file = null,
    data = {},
    success = () => {},
    failed = () => {},
    showResult = true,
    Url = '/api/common/upload'
} = {}) {
    if(!file) {
        return new Promise((resolve,reject)=>{
            reject(new Error('未选择有效文件'))
        })
    }
    let formdata = new FormData()
    formdata.append("file", file)
    for (const key in data) {
        if (data.hasOwnProperty(key)) {
            const ele = object[key]
            formdata.append(key, ele)
        }
    }
    let instance = axios.create({
        baseURL: '',
        headers: {
            'Content-Type': 'multipart/form-data'
        },
        withCredentials: true,
        timeout: 20000
    });
    return new Promise((resolve, reject) => {
        instance.post(Url, formdata).then(res => {
            console.log('UPLOAD_RES', res)
            var resData = res.data
            if( showResult ) {
                Toast(typeof showResult == 'string'?showResult:'上传成功')
            }
            if( resData.code < 1) {
                Toast(resData.msg||'上传失败')
                reject(new Error(resData.msg||'上传失败'))
            }else{
                success(resData)
                resolve(resData)
            }           
        }).catch(error => {
            Toast('上传失败')
            console.log(error)
            reject(error)
        })
    })
}


export {
    $ajax,
    baseUrl,
    host,
    $upload
}

export default {
    $ajax,
    baseUrl,
    host,
    $upload
}